<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\api\model\learn;

use app\api\model\Order as OrderModel;
use app\api\service\User as UserService;
use app\common\library\helper;
use app\common\model\learn\Community as CommunityModel;
use app\common\model\learn\community\Image as CommentImage;
use cores\exception\BaseException;
use think\facade\Db;

/**
 * 商品评价模型
 * Class Comment
 * @package app\api\model
 */
class Community extends CommunityModel {
	/**
	 * 隐藏字段
	 * @var array
	 */
	protected $hidden = [
		'user_id',
		'status',
		'sort',
		'order_id',
		'goods_id',
		'order_goods_id',
		'store_id',
		'is_delete',
		'update_time',
	];

	/**
	 * 获取指定商品评价列表
	 * @param int $goodsId 商品ID
	 * @param int|null $scoreType 评分 (10好评 20中评 30差评)
	 * @return \think\Paginator
	 * @throws \think\db\exception\DbException
	 */
	public function getCommentList($params): \think\Paginator {

		$userId = UserService::getCurrentLoginUserId();
		if ($params['current'] == 1) {
			$order = ['create_time' => 'desc'];
		} else {

			$order = ['is_hot' => 'desc', 'create_time' => 'asc'];
		}
		// 获取评价列表记录
		$filter = $this->getFilter($params);
		$list = $this->with(['category'])
			->where($filter)
			->where('status', 1)
			->order($order)
			->paginate(15);
		foreach ($list as &$item) {
			$is_collect = Db::name('learn_community_comment_log')->where('user_id', $userId)->where('comment_id', $item['comment_id'])->where('status', 2)->find();
			$item['is_collect'] = $is_collect ? 1 : 0;
			$is_collect = Db::name('learn_community_comment_log')->where('user_id', $userId)->where('comment_id', $item['comment_id'])->where('status', 1)->find();
			$item['is_step'] = $is_collect ? 1 : 0;
			$is_collect = Db::name('learn_community_comment_log')->where('user_id', $userId)->where('comment_id', $item['comment_id'])->where('status', 0)->find();
			$item['is_like'] = $is_collect ? 1 : 0;
			$is_comment = Db::name('learn_community')->where('parent_id', $item['comment_id'])
				->where('user_id', $userId)->find();
			$item['is_comment'] = $is_comment ? 1 : 0;

		}
		// 加载商品评价的关联数据
		return static::preload($list, ['user.avatar', 'images.file']);
	}

	/*
		*收藏
	*/
	public function collectSave($data): bool {
		$userId = UserService::getCurrentLoginUserId();
		if ($data['is_collect'] == 0) {
			Db::name('learn_community_comment_log')
				->where('status', $data['status'])->where('user_id', $userId)->where('comment_id', $data['comment_id'])->delete();

			if ($data['status'] == 2) {
				$this->where('comment_id', $data['comment_id'])->dec('collect_views', 1)->update();
			} elseif ($data['status'] == 1) {
				$this->where('comment_id', $data['comment_id'])->dec('step_views', 1)->update();
			} else {
				$this->where('comment_id', $data['comment_id'])->dec('like_views', 1)->update();
			}

			return true;

		}

		$data['comment_id'] = $data['comment_id'];

		$data['user_id'] = $userId;
		$data['create_time'] = time();
		$data['store_id'] = self::$storeId;
		unset($data['is_collect']);
		Db::name('learn_community_comment_log')->insert($data);

		if ($data['status'] == 2) {
			$this->where('comment_id', $data['comment_id'])->inc('collect_views', 1)->update();
		} elseif ($data['status'] == 1) {
			$this->where('comment_id', $data['comment_id'])->inc('step_views', 1)->update();
		} else {
			$this->where('comment_id', $data['comment_id'])->inc('like_views', 1)->update();
		}

		return true;

	}

	/**
	 * 获取指定商品评价列表 (限制数量, 不分页)
	 * @param int $goodsId 商品ID
	 * @param int $limit 限制的数量
	 * @return \think\Collection
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
	public function listRows(int $goodsId, int $limit = 5): \think\Collection {
		$filter = $this->getFilter($goodsId);
		return $this->with(['user.avatar'])
			->where($filter)
			->order(['sort' => 'asc', $this->getPk()])
			->limit($limit)
			->select();
	}

	/**
	 * 获取指定商品评价总数量
	 * @param int $goodsId
	 * @return int
	 */
	public function rowsTotal(int $goodsId): int {
		$filter = $this->getFilter($goodsId);
		return $this->where($filter)->count();
	}

	/**
	 * 获取查询条件
	 * @param int $goodsId 商品ID
	 * @param int|null $scoreType 评分 (10好评 20中评 30差评)
	 * @return array[]
	 */
	private function getFilter($param): array {
		// 查询参数
		$params = $this->setQueryDefaultValue($param, [
			'search' => '', // 文章标题
			'categoryId' => 0, // 文章分类id
			'status' => -1, // 文章状态
			'pid' => 0,
			'userId' => 0,
		]);
		// 检索查询条件
		$filter = [];
		!empty($params['search']) && $filter[] = ['content', 'like', "%{$params['search']}%"];
		// 文章分类id
		$params['categoryId'] > 0 && $filter[] = ['category_id', '=', $params['categoryId']];
		$params['userId'] > 0 && $filter[] = ['user_id', '=', $params['userId']];
		$filter[] = ['parent_id', '=', $params['pid']];

		return $filter;
	}

	/**
	 * 获取指定评分总数
	 * @param int $goodsId
	 * @return array|null|\think\Model
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
	public function getTotal(int $goodsId) {
		return $this->field([
			'count(comment_id) AS `all`',
			'count(score = 10 OR NULL) AS `praise`',
			'count(score = 20 OR NULL) AS `review`',
			'count(score = 30 OR NULL) AS `negative`',
		])->where([
			'goods_id' => $goodsId,
			'is_delete' => 0,
			'status' => 1,
		])->find();
	}

	/**
	 * 验证订单是否允许评价
	 * @param OrderModel $order
	 * @return boolean
	 */
	public function checkOrderAllowComment(OrderModel $order): bool {
		// 验证订单是否已完成
		if ($order['order_status'] != 30) {
			$this->error = '该订单未完成，无法评价';
			return false;
		}
		// 验证订单是否已评价
		if ($order['is_comment'] == 1) {
			$this->error = '该订单已完成评价';
			return false;
		}
		return true;
	}

	/**
	 * 根据已完成订单商品 添加评价
	 * @param OrderModel $order
	 * @param $goodsList
	 * @param array $data
	 * @return boolean
	 * @throws BaseException
	 */
	public function increased(array $data): bool {

		return $this->transaction(function () use ($data) {
			// 记录评价内容
			$data['store_id'] = self::$storeId;
			$data['user_id'] = UserService::getCurrentLoginUserId();

			$this->save($data);
			if (isset($data['uploaded'])) {
				// 记录评价图片`
				$this->saveAllImages($this['comment_id'], $data);
			}
			if (isset($data['parent_id'])) {
				Db::name('learn_community')->where('comment_id', $data['parent_id'])->inc('comment_views', 1)
					->update();
			}

			return true;
		});
	}

	/**
	 * 格式化 formData
	 * @param array $data
	 * @return array
	 */
	private function formatFormData(array $data): array {
		return helper::arrayColumn2Key($data, 'order_goods_id');
	}

	/**
	 * 记录评价图片
	 * @param $commentList
	 * @param $formData
	 * @return void
	 */
	private function saveAllImages($comment_id, $formData): void {
		// 生成评价图片数据
		$imageData = [];
		foreach ($formData['uploaded'] as $imageId) {
			$imageData[] = [
				'comment_id' => $comment_id,
				'image_id' => $imageId,
				'store_id' => self::$storeId,
			];
		}

		$model = new CommentImage;
		!empty($imageData) && $model->addAll($imageData) !== false;
	}
}
